package com.txw.javaCore.server.controller;

import com.txw.javaCore.api.response.BaseResponse;
import com.txw.javaCore.api.response.StatusCode;
import com.txw.javaCore.model.request.UserLoginRequest;
import com.txw.javaCore.server.service.UserService;
import com.txw.javaCore.server.util.ValidatorUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * @PROJECT_NAME: JavaCoreB2
 * @DESCRIPTION:
 * @Author: 涂玄武
 * @DATE: 2021/2/22 13:35
 */
@RestController
@RequestMapping(value = "/user")
public class UserController extends BaseController {

    //注入用户操作Service层实例
    @Autowired
    private UserService userService;

    /**
     * 用户登录成功异步写日志
     *
     * @param request
     * @param result
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public BaseResponse login(@RequestBody @Validated UserLoginRequest request, BindingResult result) {
        //检验前端用户提交的用户登录信息的合法性
        String checkRes = ValidatorUtil.checkResult(result);
        if (StringUtils.isNotBlank(checkRes)) {
            return new BaseResponse(StatusCode.InvalidParams.getCode(), checkRes);
        }
        log.info("--前端接受的请求参数：{}", request);
        BaseResponse response;
        try {
            log.info("开始处理用户登录逻辑！");
            Boolean res = userService.login(request);
            if (res) {
                //表示res=true，即用户登录成功
                response = new BaseResponse(StatusCode.Success.getCode(),"登录成功");
            } else {
                //表示res=false，即用户登录失败
                response = new BaseResponse(StatusCode.Fail.getCode(),"登录失败-账户名密码不匹配");
            }
        } catch (Exception e) {
            log.error("用户登录-异步写日志-发生异常：{}", e.getMessage());
            response = new BaseResponse(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

}
